<template>
  <div>
    <a-tree-select
      v-model="selectedValue"
      @change="handleChange"
      @click="handleClick"
      :treeData="treeData"
      :placeholder="placeholder"
      treeNodeFilterProp="title"
      allowClear
      showSearch
      :multiple="multiple"
      :dropdownStyle="{ maxHeight: maxHeight, overflow: 'auto' }"
    >
    </a-tree-select>
  </div>
</template>
<script>
import axios from 'axios'

export default {
  created() {
    this.fetch()
  },
  watch:{
    value: function() {
      this.selectedValue = this.value
    }
  },
  props: {
    value: { type: [String, Array] },
    placeholder: { type: [String], default:''},
    maxHeight: { type: [String], default: '600px' },
    multiple: { type: [Boolean], default: false },
  },
  data() {
    return {
      selectedValue: this.value,
      treeData: [],
    }
  },
  methods: {
    fetch () {
      axios({
        url: '/infra/role/getPendingResource',
        method: 'get',
        params: {},
      }).then((res) => {
        let nodes = res.data.treeData
        this.resolveTitleValue(nodes)
        this.treeData = nodes
      })
    },
    resolveTitleValue(nodes) {
      nodes.forEach((item) => {
        if (item.children) {
          this.resolveTitleValue(item.children)
        }
        item.title = this.$t(item.title)
        item.value = item.key
      })
    },
    handleChange(val) {
      // Should provide an event to pass value to Form.
      this.$emit('change', val)
    },
    handleClick() {
      this.fetch()
    },
  }
}
</script>
